package com.dys.util;

import java.sql.*;

/**
 * @className: com.dys.util.DatabaseUtil
 * @description: 封装工具类-封装获取连接&释放资源操作
 * @author: pine cone
 * @version: v1.0.0
 * @createTime: 2024/09/12 下午8:41
 */
public class DatabaseUtil {

    // 1.注册驱动
    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 2.与MySQL建立连接,获取连接对象
     *
     * @return 连接对象
     */
    public static Connection getConnection() {
        // 2.建立连接
        try {
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc_test_db?characterEncoding=utf-8", "root", "pinecone@mysql8");
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("获取Connection连接出错!!!");
        }
    }

    /**
     * 3.针对写操作的释放资源
     *
     * @param conn 释放连接对象
     * @param stmt 释放发送SQL的对象
     */
    public static void closeAll(Connection conn, Statement stmt) {
        if (conn == null || stmt == null) {
            throw new NullPointerException("参数传递的connection，statement 为 NULL");
        }
        try {
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭连接失败!!!");
        }
    }

    /**
     * 3.针对查询操作的释放资源
     *
     * @param conn 释放连接对象
     * @param stmt 释放发送SQL的对象
     * @param rs   释放查询对象
     */
    public static void closeAll(Connection conn, Statement stmt, ResultSet rs) {
        if (conn == null || stmt == null || rs == null) {
            throw new NullPointerException("参数传递的connection，statement，resultSet 为 NULL");
        }
        try {
            rs.close();
            stmt.close();
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException("关闭连接失败!!!");
        }
    }
}
